package com.it.rpc.core.server;

import com.it.rpc.IDL.user.UserResponseObj;
import com.it.rpc.core.codec.RequestBody;
import com.it.rpc.core.protocol.Request;
import com.it.rpc.core.protocol.Response;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

public class RpcServer {

    // 一个对象容器
    private Map<String, Object> session;

    private ExecutorService threadPool;

    public void register(Object object) {
        session.put(object.getClass().getInterfaces()[0].getName(), object);
    }

    public RpcServer() {
        int corePoolSize = 5;
        int maximumPoolSize = 50;
        long keepAliveTime = 60;
        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(100);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        this.threadPool = new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workingQueue, threadFactory);
        this.session = new ConcurrentHashMap<>();
    }


    // 启动服务
    public void serve() {

        try (ServerSocket serverSocket = new ServerSocket(9999)
        ) {

            Socket accept;
            System.out.println("服务端启动...");
            while ((accept = serverSocket.accept()) != null) {
                InetAddress inetAddress = accept.getInetAddress();
//                new Thread(new RpcServerThread(accept, session)).start();
                threadPool.execute(new RpcServerThread(accept, session));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
